package com.coldtech.circlecrash;

import java.util.ArrayList;
import java.util.List;

import com.coldtech.circlecrash.Square.SquareBlock;
import com.coldtech.circlecrash.units.Unit;

public class SquareField {
	private List<Square> squares;

	public SquareField(int width, int height) {
		squares = new ArrayList<Square>();
		int xAmount = (int) Math.floor(width / Square.WIDTH);
		int yAmount = (int) Math.floor(width / Square.HEIGHT);

		for (int y = 0; y < yAmount; y++) {
			for (int x = 0; x < xAmount; x++) {
				Square sq = new Square(((xAmount * y) + x) + "", x
						* Square.WIDTH, y * Square.HEIGHT);
				squares.add(sq);
				if (x > 0) {
					Square left = squares.get((xAmount * y) + x - 1);
					sq.addSquareToBlock(left);
					left.addSquareToBlock(sq);
				}

				if (y > 0) {
					Square top = squares.get(((xAmount * (y - 1)) + x));
					sq.addSquareToBlock(top);
					top.addSquareToBlock(sq);
				}
				if (x > 0 && y > 0) {
					Square topleft = squares.get((xAmount * (y - 1)) + x - 1);
					sq.addSquareToBlock(topleft);
					topleft.addSquareToBlock(sq);
				}
				if (x < xAmount && y > 0) {
					Square topright = squares.get((xAmount * (y - 1)) + x + 1);
					sq.addSquareToBlock(topright);
					topright.addSquareToBlock(sq);
				}
			}
		}
	}

	public void addUnit(Unit unit) {
		Square square = null;
		for (int i = 0; i < squares.size(); i++) {
			square = squares.get(i);
			if (square.isInSquare(unit)) {
				square.addUnit(unit);
				unit.setSquare(square);
			}
		}
	}

	public void findNewSquare(Unit unit) {
		Square sq = unit.getSquare();
		if (sq == null)
			return;

		sq.removeUnit(unit);
		SquareBlock sqb = sq.getSquareBlock();
		if (sqb.contains(unit)) {
			Square nsq = sqb.containIn(unit);
			nsq.addUnit(unit);
			unit.setSquare(nsq);
			return;
		}

		for (int i = 0; i < squares.size(); i++) {
			sq = squares.get(i);
			if (sq.isInSquare(unit)) {
				sq.addUnit(unit);
				unit.setSquare(sq);
				return;
			}
		}
		unit.setSquare(null);
	}

	public void findSquare(Unit unit) {
		Square sq = null;
		for (int i = 0; i < squares.size(); i++) {
			sq = squares.get(i);
			if (sq.isInSquare(unit)) {
				sq.addUnit(unit);
				unit.setSquare(sq);
				return;
			}
		}
		unit.setSquare(null);
	}
}
